package com.sl.transport.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sl.transport.domain.OrganDTO;
import com.sl.transport.repository.OrganRepository;
import com.sl.transport.service.OrganService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class OrganServiceImpl implements OrganService {

    @Resource
    private OrganRepository organRepository;
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public OrganDTO findByBid(Long bid) {
        return this.organRepository.findByBid(bid);
    }

    @Override
    public List<OrganDTO> findByBids(List<Long> bids) {
        return this.organRepository.findByBids(bids);
    }

    @Override
    public List<OrganDTO> findAll(String name) {
        return this.organRepository.findAll(name);
    }

    @Override
    public String findAllTree() {
        //获取到所有的机构
        List<OrganDTO> organDTOList = this.findAll(null);

        //得到一棵树
        List<Tree<Long>> treeList = TreeUtil.build(organDTOList, 0L, (dto, treeNode) -> {
            treeNode.setId(dto.getId());
            // treeNode.setParentId(dto.getParentId());
            treeNode.putAll(BeanUtil.beanToMap(dto));
            treeNode.remove("bid");
        });

        try {
            return this.objectMapper.writeValueAsString(treeList);
        } catch (JsonProcessingException e) {
            log.error("json序列化出错 data = {}", treeList, e);
        }
        return "";
    }
}
